package com.migrate.module.service.impl;

import com.migrate.module.domain.RangeScroll;
import com.migrate.module.domain.ScrollDbConfig;
import com.migrate.module.domain.ScrollDomain;
import com.migrate.module.domain.ScrollShardConfig;
import com.migrate.module.mapper.migrate.ScrollDbConfigMapper;
import com.migrate.module.service.MigrateConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 迁移配置获取
 *
 * @author zhonghuashishan
 */
@Service
public class MigrateConfigServiceImpl implements MigrateConfigService {

    // 注入了mapper，从db里查询scroll db config
    // 所以啊，全量同步的配置，是在我们配置文件里搞的，增量同步的配置，是从db配置表里查询的
    @Resource
    private ScrollDbConfigMapper scrollDBConfigMapper;
    /**
     * 存储topic对应的配置信息
     */
    private Map<String,RangeScroll> topicMap = new ConcurrentHashMap<>();

    @Override
    public List<ScrollDomain> queryScrollDomainList() {
        return scrollDBConfigMapper.queryScrollDomainList();
    }

    @Override
    public List<ScrollDbConfig> queryScrollDbConfigList(Long domainId) {
        return scrollDBConfigMapper.queryScrollDbConfigList(domainId);
    }

    @Override
    public List<ScrollShardConfig> queryScrollShardConfigList(Long domainId) {
        return scrollDBConfigMapper.queryScrollShardConfigList(domainId);
    }

    @Override
    public List<String> getDomainNames() {
        return scrollDBConfigMapper.getDomainNames();
    }

    @Override
    public List<String> getTablesToDomain(String domain) {
        return scrollDBConfigMapper.getTablesToDomain(domain);
    }

    @Override
    public Long getDomainId(String domain) {
        return scrollDBConfigMapper.getDomainId(domain);
    }

    /**
     * 根据消息主题返回对应的业务系统
     * @param topic
     * @return
     */
    @Override
    public RangeScroll getScrollConfig(String topic) {
        if (topicMap.containsKey(topic)){
            return topicMap.get(topic);
        }
        ScrollDomain dataBaseDomain = scrollDBConfigMapper.getDataBaseDomain(topic);
        // 封装对应的域
        RangeScroll rangeScroll = new RangeScroll();
        rangeScroll.setDomain(dataBaseDomain.getDomain());
        rangeScroll.setDomainId(dataBaseDomain.getId());
        topicMap.put(topic, rangeScroll);
        return rangeScroll;
    }

    @Override
    public String getSourceTableName(String domain, String sourceTableName) {
        return scrollDBConfigMapper.getSourceTableName(domain,sourceTableName);
    }
}
